﻿using System.Configuration;
using System.Data;
using System.Windows;
using ZGRemote.Server.UI.ViewModels;
using ZGRemote.Server.Core;
using System.Windows.Threading;
using HandyControl.Controls;
using System.Net.Sockets;
using ZGRemote.Server.UI.Properties;

namespace ZGRemote.Server.UI
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public MainViewModel MainViewModel { get; private set; }

        public static new App Current => (App)Application.Current;

        public Core.Server Server { get; set; }

        public App()
        {
            Server = new Core.Server();
            Server.RsaBlobKey = SettingConfig.RSACSPBLOB;
            Server.Exception += (e) =>
            {
                ProcessError(null, e);
            };
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
            TaskScheduler.UnobservedTaskException += App_DispatcherUnhandledException_;
            MainViewModel = new MainViewModel();

            if (Settings.Default.AutoListen)
            {
                Server.Start(SettingConfig.Settings.ListenIP, SettingConfig.Settings.ListenPort);
                Growl.Success(Core.Properties.Resources.ServerStart);
            }

            //#if DEBUG
            //            Server.Start();
            //#endif
        }

        private void App_DispatcherUnhandledException_(object? sender, UnobservedTaskExceptionEventArgs e)
        {
            ProcessError(sender, e.Exception);
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            ProcessError(sender, e.Exception);
            e.Handled = true;
        }

        private static void ProcessError(object? sender, Exception e)
        {
            switch (e)
            {
                case SocketException socketException:
                    if (socketException.ErrorCode == 10057) Growl.Error(Core.Properties.Resources.ClientDisconnect);
                    else if (socketException.ErrorCode == 10060) Growl.Error(Core.Properties.Resources.RequestTimeOut);
                    else Growl.Error(e.Message);
                    break;

                default:
                    Growl.Error(e.Message);
                    break;
            }
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            MainWindow mainWindow = new MainWindow(MainViewModel);
            mainWindow.Show();

        }
    }

}
